/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package main;

import aso.upna.playlist.GenericIterator;
import aso.upna.playlist.GenericList;
import aso.upna.rmi.GetCancionesInterface;
import aso.upna.rmi.ServidorProcRmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author triki
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    
    public static void main(String[] args) {
        // TODO code application logic here
        int timewait = 15000; //tiempo en milisegundos.
        int rmi_port = 1084;
        String rmi_url = "rmi://10.1.1.15:"+rmi_port+"/sin_proc";

        DirHandler dir = new DirHandler("/Volumes/CHIVOX/Users/chivo/Almacenes/Metasinproc/stored/");
        RegisterUsers reg = new RegisterUsers(dir);
        GenericList new_users = null;
        GenericList shared = null;

        ServidorProcRmi rmi = new ServidorProcRmi(1086);
        Thread rmi_thread = new Thread(rmi);
        rmi_thread.start();
        
        while(true)
        {
            try
            {
                System.out.print("||> Obteniendo usuarios...");
                GetCancionesInterface gc = (GetCancionesInterface) Naming.lookup(rmi_url);
                GenericList l = gc.loggedUsers();
                System.out.println(" "+l.getCountElements()+" elementos.");
                new_users = reg.registerUser(l);
                System.out.println("||> "+new_users.getCountElements()+" usuarios nuevos");
                GenericIterator iter = new_users.getIterator();

                if(new_users.getCountElements() > 0)
                {
                    System.out.println("+-------------------------------------+");
                    while(iter.hasNext())
                    {
                        String usr = (String)iter.current();
                        System.out.print("> Usuario: "+usr+" procesando...");
                        shared = gc.getCancionesFrom(usr);
                        dir.writeOnFile(shared, usr+".bin");
                        System.out.println("[OK]");
                        iter.next();
                    }
                    System.out.println("+-------------------------------------+");
                }
                
                Thread.sleep(timewait);
            }
            catch (NotBoundException ex){}
            catch (MalformedURLException ex) {}
            catch (RemoteException ex) {}
            catch (InterruptedException ex){}
        }
    }

}
